package com.douma;

import com.alibaba.fastjson.JSON;
import com.douma.dao.ShopDao;
import com.douma.dto.Shop;
import com.douma.utils.RedisConstants;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：抖码课堂
 *
 * @作者 : 老汤
 */

@RunWith(SpringRunner.class)
@SpringBootTest
public class SyncShop2Redis {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private Random random = new Random();

    @Test
    public void syncShop() {
        logger.info("【开始执行】同步商铺数据任务");
        // 1. 从 MySQL 中拿到所有商铺数据
        List<Shop> shops = shopDao.queryAll();
        // 2. 写到 Redis 缓存
        shops.forEach(shop -> {
            shop.setExpireTime(LocalDateTime.now().plusSeconds(RedisConstants.SHOP_LOGIC_EXPIRE_TIME));
            stringRedisTemplate.opsForValue()
                    .set(RedisConstants.SHOP_KEY + shop.getId(), JSON.toJSONString(shop));
        });
        logger.info("【结束】同步商铺数据任务");
    }
}
